package com.qqbot.impl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qqbot.core.core.Bot;
import com.qqbot.core.core.BotFactory;
import com.qqbot.impl.service.WebApiService;
import com.qqbot.impl.utils.*;
import com.qqbot.impl.vo.req.ApiRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * WebApiServiceImpl
 *
 * @author changwenpeng
 */
@Slf4j
@Service
public class WebApiServiceImpl implements WebApiService {

    @Value("${bot.goCqHttpWindow}")
    private String goCqHttpWindow;
    @Value("${bot.goCqHttpYmlWindow}")
    private String goCqHttpYmlWindow;
    @Value("${bot.goCqHttpLinux}")
    private String goCqHttpLinux;
    @Value("${bot.goCqHttpYmlLinux}")
    private String goCqHttpYmlLinux;

    private String WINDOWS_COMMAND = null;
    private String WINDOWS_BAT_FILE = null;
    private String WINDOWS_BAT_COMMANT = null;
    private String WINDOWS_YML_FILE = null;
    private String WINDOWS_QR_CODE_FILE = null;
    private String WINDOWS_DATA_FILEPATH = null;
    private String WINDOWS_SESSION_FILE = null;

    private String LINUX_START_COMMAND = null;
    private String LINUX_STOP_COMMAND = null;
    private String LINUX_YML_FILE = null;
    private String LINUX_QR_CODE_FILE = null;
    private String LINUX_DATA_FILEPATH = null;
    private String LINUX_SESSION_FILE = null;

    /**
     * 初始化配置
     */
    private void initWindowsConfig() {
        this.WINDOWS_COMMAND = System.getProperty("user.dir") + "\\bat\\start";
        WINDOWS_BAT_FILE = System.getProperty("user.dir") + "\\bat\\start.bat";
        WINDOWS_BAT_COMMANT = "cd /d " + goCqHttpWindow + " && go-cqhttp.exe faststart";
        WINDOWS_YML_FILE = goCqHttpYmlWindow;
        WINDOWS_QR_CODE_FILE = goCqHttpWindow + "qrcode.png";
        WINDOWS_DATA_FILEPATH = goCqHttpWindow + "data";
        WINDOWS_SESSION_FILE = goCqHttpWindow + "session.token";
    }

    /**
     * 初始化配置
     */
    private void initLinuxConfig() {
        LINUX_START_COMMAND = "cd " +goCqHttpLinux+ " && sh cqHttp.sh start";
        LINUX_STOP_COMMAND = "cd " +goCqHttpLinux+ " && sh cqHttp.sh stop";
        LINUX_YML_FILE = goCqHttpYmlLinux;
        LINUX_QR_CODE_FILE = goCqHttpLinux + "qrcode.png";
        LINUX_DATA_FILEPATH = goCqHttpLinux + "data";
        LINUX_SESSION_FILE = goCqHttpLinux + "session.token";
    }

    @Override
    public DataResult start(ApiRequest apiRequest) throws Exception {
        //String data = RSAUtils.privateKeyDecrypt(apiRequest.getData(), RSAUtils.PRIVATE_KEY);
        String data = apiRequest.getData();
        JSONObject jsonObject = JSONObject.parseObject(data);
        String botId = jsonObject.getString("botId");
        if (OSinfoUtils.EPlatform.Windows.equals(OSinfoUtils.getOSname())) {
            //windows
            initWindowsConfig();
            //gocqhttp正在运行
            if (WindowsCmdUtils.findProcess("go-cqhttp.exe")) {
                List<Bot> botList = BotFactory.getBots();
                if (!CollectionUtils.isEmpty(botList)) {
                    Bot bot = botList.get(0);
                    String loginBotId = bot.getLoginBotId();
                    //gocqhttp运行qq = 请求qq
                    if (null != bot && StringUtils.hasText(bot.getLoginBotId())
                            && StringUtils.hasText(botId) && StringUtils.hasText(loginBotId)
                            && botId.equals(loginBotId)) {
                        return DataResult.success();
                    }
                }
                //1.杀进程
                WindowsCmdUtils.killProc("go-cqhttp.exe");
            }
            //杀进程
            if (WindowsCmdUtils.findProcess("cmd.exe")) {
                WindowsCmdUtils.killProc("cmd.exe");
            }
            //2.修改配置文件
            YmlUtils.setYmlFile(new File(WINDOWS_YML_FILE));
            YmlUtils.saveOrUpdateByKey("account.uin", Long.valueOf("208286616"));
            //3.清缓存文件
            FileUtils.deleteEveryThing(WINDOWS_SESSION_FILE);
            //4.清登录二维码文件
            FileUtils.deleteEveryThing(WINDOWS_QR_CODE_FILE);
            //5.重启
            WindowsCmdUtils.executeCmds(WINDOWS_COMMAND, WINDOWS_BAT_FILE, WINDOWS_BAT_COMMANT);
            boolean exit = false;
            int i = 0;
            while (!exit) {
                i++;
                if(i>=10){
                    break;
                }
                exit = FileUtils.isFileExist(WINDOWS_QR_CODE_FILE);
                Thread.sleep(1000);
            }
            return DataResult.success(FileUtils.getBase64Image(WINDOWS_QR_CODE_FILE));
        }else if (OSinfoUtils.EPlatform.Linux.equals(OSinfoUtils.getOSname())) {
            //linux
            initLinuxConfig();
            //gocqhttp正在运行
            if (StringUtils.hasText(LinuxCmdUtils.getPID("go-cqhttp"))) {
                List<Bot> botList = BotFactory.getBots();
                if (!CollectionUtils.isEmpty(botList)) {
                    Bot bot = botList.get(0);
                    String loginBotId = bot.getLoginBotId();
                    //gocqhttp运行qq = 请求qq
                    if (null != bot && StringUtils.hasText(bot.getLoginBotId())
                            && StringUtils.hasText(botId) && StringUtils.hasText(loginBotId)
                            && botId.equals(loginBotId)) {
                        return DataResult.success();
                    }
                }
                //1.杀进程
                log.info(LinuxCmdUtils.getShellResult(LINUX_STOP_COMMAND));
            }
            //2.修改配置文件
            YmlUtils.setYmlFile(new File(LINUX_YML_FILE));
            YmlUtils.saveOrUpdateByKey("account.uin", Long.valueOf("208286616"));
            //3.清缓存文件
            FileUtils.deleteEveryThing(LINUX_SESSION_FILE);
            //4.清登录二维码文件
            FileUtils.deleteEveryThing(LINUX_QR_CODE_FILE);
            //5.重启
            log.info(LinuxCmdUtils.getShellResult(LINUX_START_COMMAND));
            boolean exit = false;
            int i = 0;
            while (!exit) {
                i++;
                if(i>=10){
                    break;
                }
                exit = FileUtils.isFileExist(LINUX_QR_CODE_FILE);
                Thread.sleep(1000);
            }
            return DataResult.success(FileUtils.getBase64Image(LINUX_QR_CODE_FILE));
        }
        return DataResult.fail("当前系统暂不支持启动");
    }

    @Override
    public DataResult stop(ApiRequest apiRequest) throws Exception {
        String data = apiRequest.getData();
        JSONObject jsonObject = JSONObject.parseObject(data);
        String botId = jsonObject.getString("botId");
        if (OSinfoUtils.EPlatform.Windows.equals(OSinfoUtils.getOSname())) {
            //windows
            this.initWindowsConfig();
            //1.杀进程
            if (WindowsCmdUtils.findProcess("go-cqhttp.exe")) {
                WindowsCmdUtils.killProc("go-cqhttp.exe");
            }
            if (WindowsCmdUtils.findProcess("cmd.exe")) {
                WindowsCmdUtils.killProc("cmd.exe");
            }
            //2.清缓存文件
            FileUtils.deleteEveryThing(WINDOWS_SESSION_FILE);
            //3.清登录二维码文件
            FileUtils.deleteEveryThing(WINDOWS_QR_CODE_FILE);
        }else if (OSinfoUtils.EPlatform.Linux.equals(OSinfoUtils.getOSname())) {
            //linux
            this.initLinuxConfig();
            //1.杀进程
            if (StringUtils.hasText(LinuxCmdUtils.getPID("go-cqhttp"))) {
                LinuxCmdUtils.getShellResult(LINUX_STOP_COMMAND);
            }
            //2.清缓存文件
            FileUtils.deleteEveryThing(LINUX_SESSION_FILE);
            //3.清登录二维码文件
            FileUtils.deleteEveryThing(LINUX_QR_CODE_FILE);
        }
        return DataResult.success();
    }

    @Override
    public DataResult refreshData(ApiRequest apiRequest) {
        String data = apiRequest.getData();
        JSONObject jsonObject = JSONObject.parseObject(data);
        String botId = jsonObject.getString("botId");
        List<Bot> botList = BotFactory.getBots();
        if (StringUtils.hasText(botId)) {
            if (!CollectionUtils.isEmpty(botList)) {
                Bot bot = botList.get(0);
                if (botId.equals(bot.getLoginBotId())) {
                    bot = bot.getLoginBot();
                    JSONObject res = new JSONObject();
                    res.put("botId", bot.getUserId());
                    res.put("nickName", bot.getNickName());
                    return DataResult.success(res.toJSONString());
                }
            }
        } else {
            if (!CollectionUtils.isEmpty(botList)) {
                Bot bot = botList.get(0);
                bot = bot.getLoginBot();
                if (null != bot) {
                    JSONObject res = new JSONObject();
                    res.put("botId", bot.getUserId());
                    res.put("nickName", bot.getNickName());
                    return DataResult.success(res.toJSONString());
                }
            }
            return DataResult.fail("获取机器人信息失败");
        }
        return DataResult.fail("机器人账号未在线，获取数据失败");
    }

}
